<html>
    <head>
        <title>Xendri NetSetup script v 0.1</title>
        <meta http-equiv="content-type" content="text/html; charset=utf8"/>
        <style>
            body {
                font-size: 13px;
                padding-left: 200px;
                font-family: Verdana;
            }

            h1 {
                font-size: 150%;
            }
            div#logo {
                background-image: url();
                margin-left: -210px;
                width: 500px;
                text-align: right;
                position: fixed;
                background-repeat: repeat-x;
            }
            img#logo {
                position: relative;
                left: 5px;
            }

            a img {
                border: none;
            }
        </style>
    </head>
    <body>
        <div id="logo">
            <a href="http://xendri.ru">
                <image id="logo" src=""/>
            </a>
        </div>
        <br/><br/><br/><br/>
        <?php
// packages list
        $GLOBALS['packages'] = array();

// Initial messages level
        $GLOBALS['el'] = 0;
// repository url
        define('REPO', 'http://xendri.ru/xrepo/');
// temporary directory
        define('TEMP', 'tmp');

// Distribution type
        $distr = 'd';

        e("Xendri NetSetup Script");
        lin();
        setup_package('setup');

        function e($msg) {
            $hl = $GLOBALS['el']+1;
            $tab = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $GLOBALS['el']);
            echo "<h$hl>$tab$msg</h$hl>";
//        echo '<br/>';
            flush();
            ob_end_flush();
        }

        function lin() {
            $GLOBALS['el']++;
        }

        function lout() {
            $GLOBALS['el']--;
            if ($GLOBALS['el'] < 0) $GLOBALS['el'] = 0;
        }

        function makedir($name, $def) {
            if (!file_exists($name)) {
                mkdir($name);
                e("Created: $name...");
            }
            if (is_array($def)) {
                foreach($def as $sname=>$sdef) {
                    makedir("$name/$sname", $sdef);
                }
            }
        }

        function init_file_registry() {

        }

        function wget($url, $target = NULL) {

            $url_stuff = parse_url($url);
            $port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;

            $fp = fsockopen($url_stuff['host'], $port);
            $rp = dirname($target);
            if (!is_dir($rp) && $rp) {
                if (strpos($rp, '/') !== false) $dirs = explode('/', $rp);
                elseif (strpos($rp, '\\') !== false) $dirs = explode('\\', $rp);
                else $dirs = array($rp);
                $dir = '';
                foreach ($dirs as $sd) {
                    $dir .= $sd;
                    if (!file_exists($dir)) {
                        mkdir($dir);
                    }
                    $dir .= '/';
                }
            }

            if ($target) $tp = fopen($target, "w");
            if (!$fp || (!$tp && $target)) {
                return false;
            }
            $query  = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
            $query .= 'Host: ' . $url_stuff['host'];
            $query .= "\n\n";

            fwrite($fp, $query);
            $ret = '';

            $content = false;
            $lr = 0;
            $headers = array();
            $line = '';
            while (!feof($fp)) {
                $tmp = fread($fp, 1);
                if (!$content) {
                    if (($tmp == "\n") && ($lr == 1)) {
                        $tmp = explode("\n\n", $tmp);
                        array_shift($tmp);
                        $tmp = implode("\n\n", $tmp);
                        $content = true;
                    } elseif ($tmp == "\n") {
                        $lr++;
                        if (strpos($line, ':') > -1) {
                            $line = explode(':', $line);
                            $hn = trim(array_shift($line));
                            $ht = trim(implode(':', $line));
                            $headers[$hn] = $ht;
                        } else {
                            $headers[] = $line;
                        }
                        $line = '';
                    } elseif ($tmp != "\r") {
                        $line .= $tmp;
                        $lr = 0;
                    }
                } else {
                    if (!(strpos($headers[0], 'OK') > -1)) {
                        fclose($fp);
                        fclose($tp);
                        return false;
                    }
                    if ($tp) {
                        fputs($tp, $tmp);
                    } else {
                        $ret .= $tmp;
                    }
                }
            }
            if (!$ret) $ret = true;

            fclose ($fp);
            if ($tp) fclose ($tp);
            return $ret;
        }


        function setup_package($package, $version = NULL, $distr = NULL) {
            e("Trying to download and install `$package` package...");
            lin();
            if (!$version) $version = 'actual';
            $info_file = tempnam(TEMP, '');
            $url = REPO.'packages/'.$package.'/'.$version.'/info.xml';
            e("downloading info for `$version` version of  `$package` package from $url");
            if (!wget($url, $info_file)) {
                e('downloading failed!');
                return false;
            }

            if (($info = simplexml_load_file($info_file)) == false) {
                e('Invalid XML!');
                return false;
            }

            $ov = $version;
            $av = $info->version;
            if (!$info->name && !$info->version) {
                e('Fake XML!');
                return  false;

            }
            if ($ov == 'actual') {
                e("Actual version: $av");
            }
            $pkey = "$package::$av";
            if (key_exists($pkey, $GLOBALS['packages'])) {
                e('Package already installed (or installing).');
                return true;
            }
            $GLOBALS['packages'][$pkey][] = $pkey;

            $conts = $info->xpath("//contains");
            if ($conts) {
                foreach ($conts as $cont) {
                    $cp = $cont['package'];
                    $cv = $cont['version'];

                    $GLOBALS['packages']["$cp::$cv"][] = $pkey;
                }
            }


            $deprs = $info->xpath("//contains");
            if ($deprs) {
                foreach ($deprs as $cont) {
                    $cp = $cont['package'];
                    $cv = $cont['version'];

                    unset($GLOBALS['packages']["$cp::$cv"]);
                }
            }


            $deps = $info->xpath('//depends');
            if ($deps) {
                foreach($deps as $dep) {
                    $dp = $dep['package'];
                    $dv = $dep['version'];
                    e("Dependency from $dp (ver. $dv) found.");
                    if (!setup_package($dp, $dv)) {
                        return false;
                    }
                }
            }

            e('Installing files of package '.$pkey);
            lin();
            if (!$distr) $distr = 'd';
            $xpath = "distr[@name=\"a\" or @name=\"$distr\"]/file";
            $nodes = $info->xpath($xpath);
            if ($nodes) {
                foreach($nodes as $file) {
                    if ($file['name'] == NULL) continue;
                    $url = REPO."packages/$package/$version/".$file['name'];
                    e("$file[name] from $url");
                    if (!wget($url, $file['location'])) {
                        throw new Exception("Downloading file {$file[name]} from $url failed!");
                    }
                }
            }
            lout();
            lout();

            return true;
        }

        function get_package_deps($info_xml) {

        }
        ?>
        <script>
            setTimeout("window.scrollTo(0, window.screen.height*2);", 100);
        </script>
    </body>
</html>